package com.cff.springbootwork.websocket.handler;

import java.io.IOException;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.AbstractWebSocketMessage;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import com.alibaba.fastjson.JSONObject;
import com.cff.springbootwork.websocket.dto.MessageDTO;
import com.cff.springbootwork.websocket.memory.WebSocketUser;

/**
 * websocket消息处理器
 * 
 * @author fufei
 *
 */
public class WebSocketHandler extends TextWebSocketHandler {
	protected Logger logger = LoggerFactory.getLogger(getClass());
	public static WebSocketUser users = new WebSocketUser();

	@Override
	protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
		logger.info("收到websocket消息:{}", message.toString());
		super.handleTextMessage(session, message);
		String msg = message.getPayload();
		logger.info("收到websocket消息的消息体:{}", msg);
		if (!StringUtils.isEmpty(msg)) {
			MessageDTO messageDTO = JSONObject.parseObject(msg, MessageDTO.class);
			sendMessageToUser(messageDTO.getTargetUserName(), message);
		}
	}

	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		String userName = (String) session.getAttributes().get("userName");
		if (StringUtils.isEmpty(userName)) {
			logger.error("用户不能为空！");
		}

		WebSocketUser.add(userName, session);
		MessageDTO messageDTO = new MessageDTO();
		messageDTO.setFromUserName("");
		messageDTO.setTargetUserName(userName);
		messageDTO.setMessageType(MessageDTO.Type.TYPE_NEW.getMessageType());
		messageDTO.setMessage("欢迎您！");
		session.sendMessage(new TextMessage(JSONObject.toJSONString(messageDTO)));
	}

	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
		String userName = (String) session.getAttributes().get("userName");
		if (StringUtils.isEmpty(userName)) {
			logger.error("用户不能为空！");
		}
		WebSocketUser.removeWebSocketSession(userName, session);
		super.afterConnectionClosed(session, status);
	}

	/**
	 * 给某个用户发送消息
	 *
	 * @param userName
	 * @param message
	 */
	public void sendMessageToUser(String userName, AbstractWebSocketMessage<?> message) {
		List<WebSocketSession> webUsers = WebSocketUser.getSessionByUserName(userName);
		if (webUsers == null || webUsers.size() == 0) {
			logger.error("发送给{},当前无session", userName);
			return;
		}
		logger.info("发送给{},当前session个数为：{}", userName, webUsers.size());

		for (int i = 0; i < webUsers.size(); i++) {
			WebSocketSession session = webUsers.get(i);
			try {
				if (!session.isOpen()) {
					WebSocketUser.removeWebSocketSession(userName, session);
				}
				session.sendMessage(message);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
